import { defineStore } from "pinia";

export const useStore=defineStore('cart',{
    state:()=>{
        return {
            cart:[]
        }
     },
    getters:{
        total(state){
            return state.cart.reduce((total,i)=>total+=i.price*i.count,0)
        },
        count(state){
            return state.cart.reduce((total,i)=>total+=i.count,0)
        }
    },
    actions:{
        addProduct(v){
            let index =this.cart.findIndex(item => item.id === v.id)
            if (index === -1) {
                v.count = 1
                this.cart.push(v)
            }else{
                this.cart[index].count++
            }
            console.log(this.cart);
        },
        removeProduct(id){
            let index = this.cart.findIndex(item => item.id === id)
            this.cart.splice(index,1)   
        }
    },
    persist:{
        enabled: true,
        strategies:[{
            key:'cart',
            Storage:localStorage
        }
        ]
    }
})